package com.dobbinsoft.iotechn.device.mqtt;

import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * Description:
 * User: rize
 * Date: 2020/6/30
 * Time: 16:27
 */
@Component
public class IotMqttManagerEmqxClient implements IotMqttManagerClient {

    @Value("${com.dobbinsoft.iotechn.mqtt.dashboard}")
    private String dashboard;

    @Value("${com.dobbinsoft.iotechn.mqtt.dashboard-user}")
    private String dashboardUser;

    @Value("${com.dobbinsoft.iotechn.mqtt.dashboard-password}")
    private String dashboardPassword;

    private OkHttpClient okHttpClient = new OkHttpClient();

    private static final Logger logger = LoggerFactory.getLogger(IotMqttManagerEmqxClient.class);

    private String basic;

    private String getCredentials() {
        if (!StringUtils.isEmpty(basic)) {
            return basic;
        }
        this.basic = Credentials.basic(dashboardUser, dashboardPassword);
        return basic;
    }

    @Override
    public void deleteDevice(String accessKeyId) {
        try {
            okHttpClient.newCall(new Request.Builder().url(dashboard + "/api/v4/clients/" + accessKeyId).header("Authorization", getCredentials()).delete().build()).execute();
        } catch (IOException e) {
            logger.error("[EMQX 踢出设备] IO异常", e);
        }
    }

    @Override
    public void banDevice(String accessKeyId, Integer minute) {
        //TODO 必要的时候禁用设备
//        try {
//            okHttpClient.newCall(new Request.Builder().url(dashboard + "/api/v4/clients/" + accessKeyId).header("Authorization", getCredentials()).delete().build()).execute();
//        } catch (IOException e) {
//            logger.error("[EMQX 禁用设备] IO异常", e);
//        }
    }
}
